/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package bw.os;

import java.util.*;
import java.io.*;
import javax.servlet.*;
import bw.net.*;
import bw.util.*;

public class SCPObjectHandler extends AsynchronousObjectWriter implements PersistentObjectReader
{
    public static final String KEYS_KEY = "keys";

    private SCPClient _client = null;
    private String _remoteBaseDir = null;

    public SCPObjectHandler ( ServletContext context )
    {
        super( context );
        
        String host = context.getInitParameter( "objectStore.scp.host" );
        String user = context.getInitParameter( "objectStore.scp.user" );
        String password = context.getInitParameter( "objectStore.scp.password" );
        _remoteBaseDir = context.getInitParameter( "objectStore.scp.root" );

        Log.getInstance().write( "SCPObjectHandler: " + user + "@" + host + ":" + _remoteBaseDir );

        _client = new SCPClient( host, user, password );
    }

    //implement this for asynchronous writes
    protected void asynchronousWrite ( String key, Object obj )
        throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = getObjectOutputStream( bos );
        oos.writeObject( obj );
        oos.close();

        byte [] bytes = bos.toByteArray();

        _client.uploadBytesTo( new ByteArrayInputStream( bytes ), 
                               bytes.length,
                               getFullPath( key ) );
    }

    protected void asynchronousErase ( String key )
        throws Exception
    {
        //cannot remove files with SCP as far as I know but
        //we can store null as the object for this key
        asynchronousWrite( key, null );
    }

    public Object read ( String key )
        throws Exception
    {
        byte [] bytes = _client.downloadBytesFrom( getFullPath( key ) );

        return getObjectFromStream( new ByteArrayInputStream( bytes ) );
    }

    private String getFullPath ( String name )
    {
        return _remoteBaseDir + "/" + makeFilename( name );
    }


}